package com.medic.client.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.github.pagehelper.Page;
import com.medic.entity.Assitant;
import com.medic.entity.Doctor;
import com.medic.entity.Group;
import com.medic.entity.Pharmacist;
import com.medic.entity.User;
import com.medic.entity.group.pain.Compliance;
import com.medic.entity.group.pain.Health;
import com.medic.entity.group.pain.Medic;
import com.medic.entity.group.pain.Pain;
import com.medic.entity.group.pain.Reaction;
import com.medic.entity.group.pain.SikerInfo;
import com.medic.entity.group.pain.Task;
import com.medic.entity.group.pain.TitrRecord;
import com.medic.service.impl.GroupServiceImpl;
import com.medic.service.impl.MedicServiceImpl;
import com.medic.service.impl.SikerinfoServiceImpl;
import com.medic.service.impl.TaskServiceImpl;
import com.medic.util.CacheUtil;
import com.medic.util.LoggerUtil;
import com.medic.util.StringUtil;

@Controller
@RequestMapping("/client/task")
@SessionAttributes({ "user", "doctor", "", "" })
public class TaskController {

	@Resource(name = "taskService")
	private TaskServiceImpl taskService;

	@Resource(name = "groupService")
	private GroupServiceImpl groupService;

	@Resource(name = "sikerinfoService")
	private SikerinfoServiceImpl sikerinfoService;

	@Resource(name = "medicService")
	private MedicServiceImpl medicService;

	private final String groupsKey = "groups";
	private final String tasksKey = "tasks";
	private final String pagesKey = "pages";
	private final String currentKey = "current";
	private final String statusKey = "status";
	private final String groupIdKey = "groupId";
	private final String taskKey = "task";
	private final String msgKey = "msg";
	private final String titrKey = "titr";
	private final String firstKey = "first";

	/**
	 * 患者分页朝着
	 * 
	 * @param user
	 *            session中的患者
	 * @param current
	 *            当前页
	 * @param groupId
	 *            组id
	 * @param status
	 *            状态
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryByUser")
	public String queryByPage(@ModelAttribute("user") User user, int current, int groupId, int status, Model model) {
		String result = "";
		long crDate = 0;
		try {
			if (status <= 1) {
				crDate = new Date().getTime();
			}
			List<Group> groups = groupService.getGroupByUser(user.getId());
			if (groupId == 0 && groups.size() > 0) {
				groupId = groups.get(0).getId();
			}
			Page<Task> tasks = taskService.getByPageUser(current, user.getId(), groupId, status, crDate);
			model.addAttribute(groupsKey, groups);
			model.addAttribute(tasksKey, tasks);
			model.addAttribute(pagesKey, tasks.getPages());
			model.addAttribute(currentKey, current);
			model.addAttribute(statusKey, status);
			model.addAttribute(groupIdKey, groupId);
			result = "/client/task";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params [ userId : " + user.getId() + ",groupId : "
					+ groupId + ",current : " + current + ",status : " + status + ",crDate : " + crDate + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 医生分页查找
	 * 
	 * @param doctor
	 *            医生
	 * @param current
	 *            当前页
	 * @param groupId
	 *            组id
	 * @param status
	 *            状态
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryByDoctor")
	public String queryByPage(@ModelAttribute("doctor") Doctor doctor, int current, int groupId, int status,
			Model model) {
		String result = "";
		long crDate = 0;
		try {
			if (status <= 1) {
				crDate = new Date().getTime();
			}
			List<Group> groups = groupService.getGroupByDoctor(doctor.getId());
			if (groupId == 0 && groups.size() > 0) {
				groupId = groups.get(0).getId();
			}
			Page<Task> tasks = taskService.getByPageDoctor(current, groupId, status, crDate);
			model.addAttribute(groupsKey, groups);
			model.addAttribute(tasksKey, tasks);
			model.addAttribute(pagesKey, tasks.getPages());
			model.addAttribute(currentKey, current);
			model.addAttribute(statusKey, status);
			model.addAttribute(groupIdKey, groupId);
			result = "/client/task";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params [ userId : " + doctor.getId() + ",groupId : "
					+ groupId + ",current : " + current + ",status : " + status + ",crDate : " + crDate + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 助手分页查找
	 * 
	 * @param assitant
	 *            session中的助手对象
	 * @param current
	 *            当前页
	 * @param groupId
	 *            组id
	 * @param status
	 *            状态
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryByAssitant")
	public String queryByPage(@ModelAttribute("assitant") Assitant assitant, int current, int groupId, int status,
			Model model) {
		String result = "";
		long crDate = 0;
		try {
			if (status <= 1) {
				crDate = new Date().getTime();
			}
			List<Group> groups = groupService.getGroupByAssitant(assitant.getId());
			if (groupId == 0 && groups.size() > 0) {
				groupId = groups.get(0).getId();
			}
			Page<Task> tasks = taskService.getByPageAssitant(current, groupId, status, crDate);
			model.addAttribute(groupsKey, groups);
			model.addAttribute(tasksKey, tasks);
			model.addAttribute(pagesKey, tasks.getPages());
			model.addAttribute(currentKey, current);
			model.addAttribute(statusKey, status);
			model.addAttribute(groupIdKey, groupId);
			result = "/client/task";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params [ userId : " + assitant.getId() + ",groupId : "
					+ groupId + ",current : " + current + ",status : " + status + ",crDate : " + crDate + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 药师分页查找
	 * 
	 * @param pharmacist
	 *            session中的药师对象
	 * @param current
	 *            当前页
	 * @param groupId
	 *            组id
	 * @param status
	 *            状态
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryByPharmacist")
	public String queryByPage(@ModelAttribute("pharmacist") Pharmacist pharmacist, int current, int groupId, int status,
			Model model) {
		String result = "";
		long crDate = 0;
		try {
			if (status <= 1) {
				crDate = new Date().getTime();
			}
			List<Group> groups = groupService.getGroupByPharmacist(pharmacist.getId());
			if (groupId == 0 && groups.size() > 0) {
				groupId = groups.get(0).getId();
			}
			Page<Task> tasks = taskService.getByPagePharmacist(current, groupId, status, crDate);
			model.addAttribute(groupsKey, groups);
			model.addAttribute(tasksKey, tasks);
			model.addAttribute(pagesKey, tasks.getPages());
			model.addAttribute(currentKey, current);
			model.addAttribute(statusKey, status);
			model.addAttribute(groupIdKey, groupId);
			result = "/client/task";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params [ userId : " + pharmacist.getId() + ",groupId : "
					+ groupId + ",current : " + current + ",status : " + status + ",crDate : " + crDate + " ]");
			result = "error";
		}
		return result;
	}

	@RequestMapping("/queryDetail")
	public String queryDetail(long tsId, Model model) {
		String result = "";
		try {
			Task task = taskService.getById(tsId);
			Object object = null;
			switch (task.getTsType()) {
			case 1:
				object = taskService.getPainByTsIdOrId(tsId, 0);
				result = "/client/task-pain-show";
				break;
			case 2:
				object = taskService.getReactionByTsId(tsId);
				result = "/client/task-reaction-show";
				break;
			case 3:
				object = taskService.getComplianceByTsId(tsId);
				result = "/client/task-compliance-show";
				break;
			case 4:
				object = taskService.getHealthByTsId(tsId);
				result = "/client/task-health-show";
				break;
			case 5:
				object = taskService.getTitrRecordByTsId(tsId);
				result = "/client/task-titr-show";
				break;
			case 6:
				object = taskService.getTakeRecordByTsId(tsId);
				result = "/client/task-medic-alert";
				break;
			default:
				return "error";
			}
			task.setTask(object);
			LoggerUtil.debug(task.toString());
			model.addAttribute(taskKey, task);
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params [ " + tsId + " ]");
			e.printStackTrace();
			result = "error";
		}
		return result;
	}

	/**
	 * 医生批阅
	 * 
	 * @param tsId
	 * @return
	 */
	@RequestMapping("/checkupByDoctor")
	@ResponseBody
	public Map<String, String> checkupByDoctor(long tsId) {
		Map<String, String> map = null;
		int code = 5;
		try {
			map = new HashMap<String, String>();
			if (taskService.checkup(code, tsId) == true) {
				map.put("result", "success");
			} else {
				map.put("result", "fail");
			}

		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + "params : [ tsId : " + tsId + " ]");
			map.put("result", "error");
		}
		return map;
	}

	/**
	 * 助手批阅
	 * 
	 * @param tsId
	 *            任务id
	 * @return json
	 */
	@RequestMapping("/checkupByAssi")
	@ResponseBody
	public Map<String, String> checkupByAssi(long tsId) {
		Map<String, String> map = null;
		int code = 3;
		try {
			map = new HashMap<String, String>();
			if (taskService.checkup(code, tsId) == true) {
				map.put("result", "success");
			} else {
				map.put("result", "fail");
			}

		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + "params : [ tsId : " + tsId + " ]");
			map.put("result", "error");
		}
		return map;
	}

	/**
	 * 药师批阅
	 * 
	 * @param tsId
	 * @return
	 */
	@RequestMapping("checkupByPhar")
	@ResponseBody
	public Map<String, String> checkupByPhar(long tsId) {
		Map<String, String> map = null;
		int code = 4;
		try {
			map = new HashMap<String, String>();
			if (taskService.checkup(code, tsId) == true) {
				map.put("result", "success");
			} else {
				map.put("result", "fail");
			}

		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + "params : [ tsId : " + tsId + " ]");
			map.put("result", "error");
		}
		return map;
	}

	@RequestMapping("/doTask")
	public String doTask(long tsId, Model model) {
		String result = "";
		try {
			Task task = taskService.getById(tsId);
			LoggerUtil.debug(task.toString());
			long crDate = new Date().getTime();
			if (crDate < task.getCrDate()) {
				model.addAttribute(taskKey, task);
				switch (task.getTsType()) {
				case 1:
					SikerInfo info = CacheUtil.getSikerinfos().get(task.getSikerId()+""+task.getGroupId());
					if(info.getIsFirst() == 1){
						model.addAttribute("first", true);
					}
					result = "/client/task-pain-add";
					break;
				case 2:
					result = "/client/task-reaction-add";
					break;
				case 3:
					result = "/client/task-compliance-add";
					break;
				case 4:
					result = "/client/task-health-add";
					break;
				// 滴定任务比较特殊，放出来
				// case 5:
				// result = "/client/task-titr-add";
				// break;
				case 6:
					result = "/client/task-medic-alert";
					Object object = taskService.getTakeRecordByTsId(tsId);
					task.setTask(object);
					break;
				default:
					break;
				}

			} else {
				model.addAttribute(msgKey, "该任务已经过期");
				result = "result";
			}
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ tsId : " + tsId + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 做滴定任务
	 * 
	 * @param user
	 *            患者
	 * @param groupId
	 *            组id
	 * @param tsId
	 *            任务id
	 * @param model
	 * @return
	 */
	@RequestMapping("/doTitr")
	public String doTitr(@ModelAttribute("user") User user, int groupId, int tsId, Model model) {
		String result = "";
		try {
			Task task = taskService.getById(tsId);
			LoggerUtil.debug(task.toString());
			long crDate = new Date().getTime();
			SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + groupId);
			if (crDate < task.getCrDate() && info != null) {
				model.addAttribute(taskKey, task);
				switch (info.getIsTitr()) {
				case 2:
					result = "task-titr-sure";
					List<TitrRecord> list = taskService.getTitrRecordByTsId(tsId); // 按照titrId降序排序
					TitrRecord titr = list.get(0); // 第0个即使最新的
					model.addAttribute(titrKey, titr);
					break;
				case 3:
					result = "task-pain-add";
					break;
				default:
					break;
				}
			} else {
				model.addAttribute(msgKey, "任务过期");
				result = "result";
			}
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",groupId : "
					+ groupId + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 添加疼痛反馈
	 * 
	 * @param user
	 *            患者
	 * @param pain
	 *            疼痛对象
	 * @param model
	 * @return
	 */
	@RequestMapping("/addPain")
	public String add(@ModelAttribute("user") User user, Pain pain, Model model) {
		String result = "";
		LoggerUtil.debug(pain.toString());
		try {
			int groupId = 0;
			if ((groupId = taskService.judge(pain.getTsId(), user.getId())) > 0 && taskService.savePain(pain)
					&& taskService.finsh(pain.getTsId(), user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				// if (info.getIsTitr() == 1) {
				if (pain.getPainLevel() >= 4) {
					info.setCoPain(info.getCoPain() + 1);
					if (info.getCoPain() >= 3) {
						sikerinfoService.endEvalById(info.getId());
						CacheUtil.getSikerinfos().remove(user.getId() + "" + groupId);
						model.addAttribute(msgKey, "您一直处于高疼痛状态，建议您立刻就医！");
					} else {
						info.setPainDate(info.getPainDate() - 2 * StringUtil.DAY);
						SikerInfo newInfo = new SikerInfo();
						newInfo.setId(info.getId());
						newInfo.setPainDate(info.getPainDate());
						newInfo.setCoPain(info.getCoPain());
						// 还需要在数据库中进行更新
						sikerinfoService.update(newInfo);
						model.addAttribute(msgKey, "任务完成");
					}
				} else {
					if (info.getCoPain() > 0) {
						info.setCoPain(0);
						SikerInfo newInfo = new SikerInfo();
						newInfo.setCoPain(0);
						newInfo.setId(info.getId());
						// 在数据库中更新
						sikerinfoService.update(newInfo);
					}
					model.addAttribute(msgKey, "任务完成");
				}
				// } else {
				// List<TitrRecord> titrs =
				// taskService.getTitrRecordByTsId(pain.getTsId());
				// TitrRecord titr = titrs.get(0);
				// // 时间在service方法中
				// taskService.updateTitrRecord(titr.getTitrId(),
				// pain.getPainId(), pain.getPainLevel());
				// info.setTitrNum(info.getTitrNum() + 1);
				// if (info.getTitrNum() >= 12) {
				// // 利用计算公式得出患者每日需要服药的量
				// info.setIsTitr(1); // 设置患者处于非滴定任务状态下
				// } else {
				// info.setIsTitr(2);
				//
				// double amounts = titr.getAmounts();
				// String medicName = "吗啡";
				// TitrRecord newTitr = null;
				//
				// if (info.getIsTolerance() == 1 && pain.getPainLevel() >= 4) {
				// if (info.getTitrNum() == 1) {
				// for (Map.Entry<Integer, Medic> entry :
				// CacheUtil.getMedics().entrySet()) {
				// Medic medic = entry.getValue();
				// if (medic.getSikerId() == user.getId()
				// && medic.getMedicName().equals(StringUtil.MEDIC_NAME)) {
				// amounts = medic.getAlert().get(0).getAmounts();
				// break;
				// }
				// }
				// medicName = "羟考酮";
				// } else if (info.getTitrNum() == 2) {
				// if (pain.getPainLevel() >= 4 && pain.getPainLevel() < 7) {
				// amounts = 10;
				// } else if (pain.getPainLevel() >= 7) {
				// amounts = 15;
				// }
				// } else {
				// if (pain.getPainLevel() >= 7) {
				// amounts = amounts * 0.5;
				// }
				// }
				// newTitr = new TitrRecord();
				// newTitr.setMedicName(medicName);
				// newTitr.setAmounts(amounts);
				// newTitr.setTsId(pain.getTsId());
				// newTitr.setTakeway("口服");
				// taskService.saveTitrRecord(newTitr);
				// // 发一条微信消息通知患者进行服药确认。
				//
				// // 修改滴定任务的过期时间
				// taskService.updateTitrCrDate(new Date().getTime() + 3600000,
				// pain.getTsId());
				// }
				// }
				// model.addAttribute(msgKey, "任务完成");
				// }
			} else {
				model.addAttribute(msgKey, "任务失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ pain : " + pain + " ]");
			result = "error";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 添加不良反应
	 * 
	 * @param user
	 *            患者
	 * @param reaction
	 *            不良反应对象
	 * @param model
	 * @return
	 */
	@RequestMapping("/addReaction")
	public String add(@ModelAttribute("user") User user, Reaction reaction, Model model) {
		String result = "";
		LoggerUtil.debug(reaction.toString());
		try {
			int groupId;
			if ((groupId = taskService.judge(reaction.getTsId(), user.getId())) > 0
					&& taskService.saveReaction(reaction) && taskService.finsh(reaction.getTsId(), user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				info.setRcDate(info.getRcDate() + 3 * StringUtil.DAY);
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				newInfo.setRcDate(info.getRcDate());
				sikerinfoService.update(newInfo);
				model.addAttribute(msgKey, "任务完成");
			} else {
				model.addAttribute(msgKey, "任务失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",reaction : "
					+ reaction + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 添加依从性
	 * 
	 * @param user
	 *            患者
	 * @param compliance
	 *            依从性对象
	 * @param model
	 * @return
	 */
	@RequestMapping("/addCompliance")
	public String add(@ModelAttribute("user") User user, Compliance compliance, Model model) {
		String result = "";
		LoggerUtil.debug(compliance.toString());
		try {
			int groupId;
			if ((groupId = taskService.judge(compliance.getTsId(), user.getId())) > 0
					&& taskService.saveCompliance(compliance)
					&& taskService.finsh(compliance.getTsId(), user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				info.setCpDate(info.getCpDate() + 15 * StringUtil.DAY);
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				newInfo.setCpDate(info.getCpDate());
				sikerinfoService.update(newInfo);
				model.addAttribute(msgKey, "任务完成");
			} else {
				model.addAttribute(msgKey, "任务失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",compliance : "
					+ compliance + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 添加健康评估
	 * 
	 * @param user
	 *            患者
	 * @param tiValue
	 *            每个题目的值
	 * @param tsId
	 *            任务id
	 * @param model
	 * @return
	 */
	@RequestMapping("/addHealth")
	public String add(@ModelAttribute("user") User user, String tiValue, long tsId, Model model) {
		String result = "";
		try {
			LoggerUtil.debug(tiValue);
			String[] value = tiValue.trim().split(",");
			Health health = null;
			List<Health> hls = new ArrayList<Health>();
			for (int i = 0; i < value.length; i++) {
				health = new Health();
				health.setTiNo(i + 1);
				health.setTiValue(Integer.valueOf(value[i]));
				health.setTsId(tsId);
				hls.add(health);
			}
			int groupId;
			if ((groupId = taskService.judge(tsId, user.getId())) > 0 && taskService.saveHealth(hls) > 0
					&& taskService.finsh(tsId, user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				info.setHlDate(info.getHlDate() + 30 * StringUtil.DAY);
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				newInfo.setHlDate(info.getHlDate());
				sikerinfoService.update(newInfo);
				model.addAttribute(msgKey, "任务完成");
			} else {
				model.addAttribute(msgKey, "任务失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",tiValue : "
					+ tiValue + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 服药提醒确认
	 * 
	 * @param user
	 *            患者
	 * @param tsId
	 *            任务id
	 * @return
	 */
	@RequestMapping("sureAlert")
	@ResponseBody
	public String sureAlert(@ModelAttribute("user") User user, long tsId) {
		String result = "";
		try {
			if (taskService.judge(tsId, user.getId()) > 0 && taskService.finsh(tsId, user.getId())) {
				result = "{\"result\":\"success\"}";
			} else {
				result = "{\"result\":\"fail\"}";
			}
		} catch (Exception e) {
			LoggerUtil.error(
					"error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",tsId : " + tsId + " ]");
			result = "{\"result\":\"error\"}";
		}
		return result;
	}

	/**
	 * 确认 滴定任务中的服药，确认后有部分后续操作需要注意。
	 * 
	 * @param titrId
	 *            滴定服药记录id
	 * @param user
	 *            患者
	 * @param groupId
	 *            组id（获取入组信息必须的）
	 * @return
	 */
	@RequestMapping("/sureTitr")
	@ResponseBody
	public String sureTitr(@ModelAttribute(StringUtil.USER_KEY) User user, int groupId, int titrId) {

		String result = "";
		try {
			if (taskService.sureTake(titrId)) {
				// 设置一小时后提醒用户进行疼痛评价
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				info.setTrDate(new Date().getTime() + StringUtil.HOUR);
				info.setIsTitr(3);
				// 对数据也进行更新
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				newInfo.setTrDate(info.getTrDate());
				newInfo.setIsTitr(3);
				sikerinfoService.update(newInfo);
				result = "{\"result\":\"success\"}";
			} else {
				result = "{\"result\":\"fail\"}";
			}
		} catch (Exception e) {
			result = "{\"result\":\"error\"}";
		}

		return result;
	}

	/**
	 * 添加滴定过程中的疼痛评价
	 * 
	 * @param user
	 *            患者
	 * @param pain
	 *            疼痛评价
	 * @param model
	 * @return 如果滴定任务
	 */
	@RequestMapping("/addTitrPain")
	public String addTitrPain(@ModelAttribute(StringUtil.USER_KEY) User user, Pain pain, Model model) {
		String result = "";
		try {
			int groupId;
			if ((groupId = taskService.judge(pain.getTsId(), user.getId())) > 0 && taskService.savePain(pain)) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				info.setTitrNum(info.getTitrNum() + 1); // 滴定次数
				info.setIsTitr(2); // 进入滴定服药
				info.setPainLevel(pain.getPainLevel()); // 疼痛评分
				// 数据库中更新的对象
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				newInfo.setTitrNum(info.getTitrNum());
				newInfo.setIsTitr(info.getIsTitr());
				newInfo.setPainLevel(pain.getPainLevel());

				// 进行了12次滴定，然后就完成滴定
				if (info.getTitrNum() >= 12) {

					taskService.finsh(pain.getTsId(), user.getId());
					// 完成滴定，跟新入组信息
					info.setIsTitr(1);
					info.setTrDate(new Date().getTime());
					newInfo.setIsTitr(1);
					newInfo.setTrDate(info.getTrDate());

					// 开始正常的疼痛评分 当前评分
					if (pain.getPainLevel() >= 4) {
						info.setPainDate(info.getTrDate() + StringUtil.DAY);
					} else {
						info.setPainDate(info.getTrDate() + 3 * StringUtil.DAY);
					}
					newInfo.setPainDate(info.getPainDate());

					// 利用公式计算出，每天应该服用的总量，至于是否需要设置到羟考酮的用药提醒中，暂时没有。

					// 更新入组信息

					model.addAttribute(msgKey, "滴定完成，您每天服药" + "num");
					result = "result";
				} else {
					// 疼痛评价完了马上进行服药，暂时没有进行为新消息提醒
					TitrRecord titr = taskService.getTitrRecordByTsId(pain.getTsId()).get(0);
					titr = taskService.saveTitrRecord(info, titr.getAmounts());
					model.addAttribute(titrKey, titr);
					model.addAttribute(groupIdKey, groupId);
					result = "/client/task-titr-sure";
				}
				sikerinfoService.update(newInfo);
			} else {
				result = "result";
				model.addAttribute(msgKey, "任务失败");
			}
		} catch (Exception e) {
			result = "error";
		}
		return result;
	}

	// 一下即是申请入组时候以及申请通过后的流程，由于这段流程比较复杂，而且多数参数需要进行初始化，所以重点注意

	@RequestMapping("/goJudge")
	public String goJudge(int groupId, Model model) {
		String result = "/client/task-judge";
		LoggerUtil.debug(groupId + "");
		model.addAttribute(groupIdKey, groupId);
		return result;
	}

	/**
	 * 申请入组开始的流程 （判定是否耐受、是否带有吗啡）
	 * 
	 * @param user
	 *            患者
	 * @param groupId
	 *            组id
	 * @param nums
	 *            每天的服药次数（string类型 由，分隔）
	 * @param amounts
	 *            每次服药量（string类型 由，分隔）
	 * @param days
	 *            服了多少天（string类型 由，分隔）
	 * @param haveMarfei
	 *            是否带有吗啡
	 * @param model
	 * @return
	 */
	@RequestMapping("judgeInfo")
	public String judgeSikerinfo(@ModelAttribute(StringUtil.USER_KEY) User user, int groupId, String nums,
			String amounts, String days, int haveMarfei, int haveAos, Model model) {
		String result = "";
		try {
			SikerInfo info = new SikerInfo();
			info.setGroupId(groupId);
			info.setSikerId(user.getId());
			info.setIsTolerance(1);
			String[] sNum = nums.trim().split(",");
			String[] sAmou = amounts.trim().split(",");
			String[] sDay = days.trim().split(",");
			for (int i = 0; i < 2; i++) {
				int num = Integer.parseInt(sNum[i]) * Integer.parseInt(sAmou[i]);
				int day = Integer.parseInt(sDay[i]);
				switch (i) {
				case 0:
					if (num >= 30 && day >= 7) {
						info.setIsTolerance(2);
					}
					break;
				case 1:
					if (num >= 60 && day >= 7) {
						info.setIsTolerance(2);
					}
					break;
				default:
					break;
				}
				// 判断已经是耐受了，直接break
				if (info.getIsTolerance() == 2) {
					break;
				}
			}
			info.setHaveMarfei(haveMarfei);
			info.setHaveAos(haveAos);
			// 是第一次疼痛评价（由于刚刚入组）
			info.setIsFirst(1);
			sikerinfoService.save(info);
			CacheUtil.getSikerinfos().put(info.getSikerId() + "" + info.getGroupId(), info);
			// 入组信息创建完成，就立刻进行依从性评价
			Task task = new Task();
			task.setSikerId(user.getId());
			task.setGroupId(groupId);
			// 设置依从性评价过期时间为两天后
			task.setCrDate(new Date().getTime() + 2 * StringUtil.DAY);
			task.setTsType(3); // 任务类型
			taskService.save(task); // 添加任务

			model.addAttribute(taskKey, task);
			result = "/client/task-compliance-add";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",groupid : "
					+ groupId + ",nums : " + nums + ",amounts : " + amounts + ",days : " + days + " ]");
			result = "error";
		}
		return result;
	}

	/**
	 * 入组的时候第一次进行疼痛评估（该任务需要在确认患者入组的时候生成）
	 * 
	 * @param user
	 *            患者
	 * @param pain
	 *            疼痛评估
	 * @param model
	 * @return
	 */
	@RequestMapping("/evalPain")
	public String evalPain(@ModelAttribute(StringUtil.USER_KEY) User user, Pain pain, Model model) {
		String result = "";
		try {
			int groupId;
			if ((groupId = taskService.judge(pain.getTsId(), user.getId())) > 0 && taskService.savePain(pain)
					&& taskService.finsh(pain.getTsId(), user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				// 为了对数据中的数据进行更新
				SikerInfo newInfo = new SikerInfo();
				newInfo.setId(info.getId());
				// 疼痛大于四 而且 带有吗啡
				if (pain.getPainLevel() >= 4 && info.getHaveMarfei() == 2) {
					info.setIsTitr(2);
					info.setTitrNum(0);
					// 设置患者需要进行滴定任务
					newInfo.setIsTitr(2);
				} else {
					info.setIsTitr(1);
					info.setPainDate(new Date().getTime() + 3 * StringUtil.DAY);
					newInfo.setIsTitr(1);
					newInfo.setPainDate(info.getPainDate());
				}
				// 设置疼痛评价不是第一次
				info.setIsFirst(2);
				newInfo.setIsFirst(2);
				sikerinfoService.update(newInfo);
				// 添加一个不良反馈任务
				Task task = new Task();
				task.setSikerId(user.getId());
				task.setGroupId(groupId);
				task.setCrDate(new Date().getTime() + StringUtil.DAY);
				task.setTsType(2);
				taskService.save(task);
				// 跳转页面做不良反馈
				model.addAttribute(taskKey, task);
				model.addAttribute(firstKey, "true");
				result = "/client/task-reaction-add";
			} else {
				model.addAttribute(msgKey, "任务失败");
				result = "result";
			}
		} catch (Exception e) {
			result = "error";
		}
		return result;
	}

	/**
	 * 入组时疼痛评价完后的不良反馈 ，完成后如果需要进行滴定，则马上进入滴定阶段。
	 * 
	 * @param user
	 *            患者
	 * @param reaction
	 *            不良反应
	 * @param model
	 * @return
	 */
	@RequestMapping("/evalReaction")
	public String evalReaction(@ModelAttribute(StringUtil.USER_KEY) User user, Reaction reaction, Model model) {
		String result = "";
		try {
			int groupId;
			if ((groupId = taskService.judge(reaction.getTsId(), user.getId())) > 0
					&& taskService.saveReaction(reaction) && taskService.finsh(reaction.getTsId(), user.getId())) {
				SikerInfo info = CacheUtil.getSikerinfos().get(user.getId() + "" + groupId);
				if (info.getIsTitr() == 2) {
					// 添加一个滴定任务
					Task task = new Task();
					task.setSikerId(user.getId());
					task.setGroupId(groupId);
					task.setCrDate(new Date().getTime() + StringUtil.HOUR);
					task.setTsType(5);
					taskService.save(task);

					info.setTrTsId(task.getTsId());

					TitrRecord titr = taskService.saveTitrRecord(info, 0);
					model.addAttribute(titrKey, titr);
					return "/client/task-titr-sure";
				} else {
					model.addAttribute(msgKey, "任务完成");
				}

			} else {
				model.addAttribute(msgKey, "任务失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",reaction : "
					+ reaction.toString() + " ]");
		}
		return result;
	}

}
